<template>
	<el-dialog v-model="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="false"
		class="flex-align" style="width: 100%;height: 100%;padding: 30px 24px;margin: 0;background: transparent;">
		<template #header>
			<el-card style="width: 100%;height: 100%;" body-style="padding: 0;" shadow="never">
				<template #header>
					<div class="flex-space-between">
						<div>
							<el-text style="font-size: 16px;">
								采购需求
							</el-text>
						</div>
						<div>
							<el-button @click="closeDialog">取消</el-button>
							<!-- <el-button @click="closeDialog">
								保存并继续创建
								<el-icon style="margin-left: 4px;">
									<ArrowDown />
								</el-icon>
							</el-button> -->
							<el-button type="primary" @click="submitForm(vFormRef)">
								保存
							</el-button>
						</div>
					</div>
				</template>
				<el-scrollbar ref="scrollbarRef" @scroll="handleScroll"
					:style="`height: calc(100vh - 69px - ( 30px + 30px));`">
					<el-form :model="formData" :rules="rules" ref="vFormRef" label-position="top" label-width="50px"
						style="padding: 16px;">
						<el-form-item label="状态" prop="procurementDemandStatusId">
							<el-input v-model="formData.procurementDemandStatusId" readonly type="text" clearable
								class="my">
								<template #prefix>
									<div>
										<el-check-tag
											:style="`color: ${procurementDemandStatusIndex===key?'#fff':''};${procurementDemandStatusIndex===key?`background: ${item.bg}`:''}`"
											v-for="(item,key) in procurementDemandStatusTags" :key="key"
											:checked="procurementDemandStatusIndex===key"
											@change="tagChange(key,'procurementDemandStatusId')">{{item.text}}</el-check-tag>
									</div>
								</template>
							</el-input>
						</el-form-item>
						<el-form-item label="类型" prop="procurementDemandType">
							<el-input v-model="formData.procurementDemandType" readonly type="text" clearable
								class="my">
								<template #prefix>
									<div>
										<el-check-tag
											:style="`color: ${procurementDemandIndex===key?'#fff':''};${procurementDemandIndex===key?`background: ${item.bg}`:''}`"
											v-for="(item,key) in procurementDemandTags" :key="key"
											:checked="procurementDemandIndex===key"
											@change="tagChange(key,'procurementDemandType')">{{item.text}}</el-check-tag>
									</div>
								</template>
							</el-input>
						</el-form-item>
						<div class="static-content-item">
							<div>需求产品</div>
						</div>
						<el-form-item label="需求仓库" prop="warehouse">
							<el-select @clear="selectClear('warehouse')" v-model="formData.warehouse"
								@change="(value:any)=>selectChange(value,'warehouse')" multiple ref="warehouse"
								clearable>
								<el-option v-for="item in warehouseOption" :key="key" :label="item?.label"
									:value="item?.value">
									<!--  -->
									<div class="flex-align-center">
										<el-icon :color="item?.color">
											<component :is="item?.icon"></component>
										</el-icon>
										<!--  -->
										<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
									</div>
								</el-option>
								<!--  -->
								<template #tag>
									<div class="flex-align-center">
										<el-icon :color="warehouseOption[warehouseIndex]?.color">
											<component :is="warehouseOption[warehouseIndex]?.icon">
											</component>
										</el-icon>
										<!--  -->
										<el-text size="small"
											style="margin-left: 6px;">{{warehouseOption[warehouseIndex]?.label}}</el-text>
									</div>
								</template>
							</el-select>
						</el-form-item>
						<el-form-item label="需求产品" prop="product">
							<el-select @clear="selectClear('product')" v-model="formData.product"
								@change="(value:any)=>selectChange(value,'product')" multiple ref="product" clearable>
								<el-option v-for="item in productOption" :key="key" :label="item?.label"
									:value="item?.value">
									<!--  -->
									<div class="flex-align-center">
										<el-icon :color="item?.color">
											<component :is="item?.icon"></component>
										</el-icon>
										<!--  -->
										<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
									</div>
								</el-option>
								<!--  -->
								<template #tag>
									<div class="flex-align-center">
										<el-icon :color="productOption[productIndex]?.color">
											<component :is="productOption[productIndex]?.icon">
											</component>
										</el-icon>
										<!--  -->
										<el-text size="small"
											style="margin-left: 6px;">{{productOption[productIndex]?.label}}</el-text>
									</div>
								</template>
							</el-select>
						</el-form-item>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="需求数量" prop="demandAmount">
									<el-input v-model="formData.demandAmount" placeholder="请填写"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="预计采购单价" prop="expectedUnitPrice">
									<el-input v-model="formData.expectedUnitPrice" placeholder="请填写"></el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-form-item label="预计采购总额" prop="expectedTotalAmount">
							<el-input v-model="formData.expectedTotalAmount" disabled placeholder="自动计算结果"></el-input>
						</el-form-item>
						<div class="static-content-item">
							<div>需求详情</div>
						</div>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="期望到货日期" prop="expectedArrivalDate">
									<el-date-picker v-model="formData.expectedArrivalDate" style="width:100%;"
										type="date" />
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="期望供应商" prop="expectedSupplier">
									<el-select @clear="selectClear('expectedSupplier')"
										v-model="formData.expectedSupplier"
										@change="(value:any)=>selectChange(value,'expectedSupplier')" multiple
										ref="expectedSupplier" clearable>
										<el-option v-for="item in expectedSupplierOption" :key="key"
											:label="item?.label" :value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div class="flex-align-center">
												<el-icon :color="expectedSupplierOption[expectedSupplierIndex]?.color">
													<component
														:is="expectedSupplierOption[expectedSupplierIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{expectedSupplierOption[expectedSupplierIndex]?.label}}</el-text>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-form-item label="需求描述" prop="description">
							<el-input v-model="formData.description" type="textarea" placeholder="请填写"></el-input>
						</el-form-item>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="申请日期" prop="applyDate">
									<el-date-picker placeholder="请选择" v-model="formData.applyDate" style="width:100%;"
										type="date" />
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="申请人" prop="applicant">
									<el-input placeholder="请填写" v-model="formData.applicant"></el-input>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</el-scrollbar>
				<!--  -->
			</el-card>
			<levitation ref="levitationRef" :types="types" :params="levitationParams" :observerElement="scrollbarRef"
				:options="options" :element="element" @change="levitationChange" />
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import request from '../../../utils/request';
	import { UploadFilled, Ticket, Ship, WalletFilled, CirclePlus, DocumentAdd, Delete } from '@element-plus/icons-vue';
	import { mergeObjects, formatNumber } from '../../../utils';
	import { useSelect } from '../../../utils/mixins';
	import levitation from '../../../components/levitation-form/levitation-form.vue';
	import { getShipments } from '../../../api/shipmentAPI';
	import { jwtDecode } from 'jwt-decode';
	import cookie from 'js-cookie';
	import { ElMessage, FormInstance } from 'element-plus';
	const emits = defineEmits(['update']);
	const { handSelectChange } = useSelect();
	const router = useRouter();
	const route = useRoute();
	const vFormRef = ref(null);
	const loading = ref(false);

	// 表单
	const formData = ref({
		procurementDemandStatusId: null,
		procurementDemandType: null,
		warehouseId: null,
		warehouse: [],
		productId: null,
		product: [],
		demandAmount: null,
		expectedUnitPrice: null,
		expectedTotalAmount: null,
		expectedArrivalDate: null,
		expectedSupplierId: null,
		expectedSupplier: null,
		description: null,
		applyDate: null,
		applicant: null,
	});
	//验证
	const rules = reactive({
		procurementDemandStatusId: [{
			required: true,
			message: '状态不能为空',
			trigger: 'blur'
		}],
		procurementDemandType: [{
			required: true,
			message: '类型不能为空',
			trigger: 'blur'
		}],
		warehouse: [{
			required: true,
			message: '需求仓库不能为空',
			trigger: 'blur'
		}],
		product: [{
			required: true,
			message: '需求产品不能为空',
			trigger: 'blur'
		}],
		demandAmount: [{
			required: true,
			message: '需求数量不能为空',
			trigger: 'blur'
		}],
		expectedUnitPrice: [{
			required: true,
			message: '预计采购单价不能为空',
			trigger: 'blur'
		}],
		expectedTotalAmount: [],
		expectedArrivalDate: [{
			required: true,
			message: '期望到货日期不能为空',
			trigger: 'blur'
		}],
		expectedSupplier: [{
			required: true,
			message: '期望供应商不能为空',
			trigger: 'blur'
		}],
		description: [],
		applyDate: [{
			required: true,
			message: '申请日期不能为空',
			trigger: 'blur'
		}],
		applicant: [{
			required: true,
			message: '申请人不能为空',
			trigger: 'blur'
		}]
	});
	const pageData = ref({
		pageNum: 1,
		pageSize: 1000,
		total: 0,
		pages: 0,
	});
	//状态
	const procurementDemandStatusTags = ref([]);
	const procurementDemandStatusIndex = ref(-1);
	//类型
	const procurementDemandTags = ref([]);
	const procurementDemandIndex = ref(-1);
	//需求仓库
	const warehouseOption = ref([]);
	const warehouseIndex = ref(-1);
	const warehouse = ref(null);
	//需求产品
	const productOption = ref([]);
	const productIndex = ref(-1);
	const product = ref(null);
	//期望供应商
	const expectedSupplierOption = ref([]);
	const expectedSupplierIndex = ref(-1);
	const expectedSupplier = ref(null);
	//
	const dialogVisible = ref(false);
	/**
	 * 打开弹出层
	 */
	const openDialog = () => {
		dialogVisible.value = true;
		setTimeout(async () => {
			const result = await getPageId();
			//
			if (result) {
				getprocurementDemandStatusList();
				getprocurementDemandList();
				getwarehouseAll();
				getexpectedSupplierAll();
				
				if(!route.query.id){
					procurementDemandStatusIndex.value = 0;
					formData.value.procurementDemandStatusId = 142;
				}
			}
		}, 10);
	}
	/**
	 * 关闭弹出层
	 */
	const closeDialog = () => {
		dialogVisible.value = false;
		vFormRef.value.resetFields();
		//清空url参数
		router.push({ query: {} });
	}
	//获取当前页面的数据
	const getPageId = async () => {
		if (!route.query.id) {
			const token = cookie.get('token');
			const decodedToken : {
				username : string
			} = jwtDecode(token);
			// console.log('decodedToken--->', decodedToken);
			//
			formData.value.applicant = decodedToken?.username;
			//
			return true;
		}
		//
		const result = await request({
			url: '/demand/selectDemandById',
			params: {
				demandId: route.query.id
			},
		});
		//
		console.log('getPageId --->', result);
		//
		formData.value = { ...result.data.t };
		return true;
	}
	//改变
	const selectChange = (value : Array<any>, type : string, key : number) => {
		//所有下拉框的配置列表
		const typeList = [{
			type: 'warehouse', //哪一个下拉框，根据ref
			option: warehouseOption, //下拉列表选项
			indexVar: warehouseIndex, //当前选中项
			idVar: 'warehouseId', //当前id值
			blurRef: warehouse, //ref
			fun: getproductById
		}, {
			type: 'product', //哪一个下拉框，根据ref
			option: productOption, //下拉列表选项
			indexVar: productIndex, //当前选中项
			idVar: 'productId', //当前id值
			blurRef: product, //ref
		}, {
			type: 'expectedSupplier', //哪一个下拉框，根据ref
			option: expectedSupplierOption, //下拉列表选项
			indexVar: expectedSupplierIndex, //当前选中项
			idVar: 'expectedSupplierId', //当前id值
			blurRef: expectedSupplier, //ref
		}];
		//
		handSelectChange(formData, typeList, value, type, key);
	}
	//tag改变
	const tagChange = (index : number, type : string) => {
		// if (type === 'procurementDemandStatusId') {
		// 	if (procurementDemandStatusIndex.value === index) {
		// 		formData.value[type] = null;
		// 		procurementDemandStatusIndex.value = -1;
		// 		return;
		// 	}
		// 	procurementDemandStatusIndex.value = index;
		// 	formData.value[type] = procurementDemandStatusTags.value[index].value;
		// }
		if (type === 'procurementDemandType') {
			if (procurementDemandIndex.value === index) {
				formData.value[type] = null;
				procurementDemandIndex.value = -1;
				return;
			}
			procurementDemandIndex.value = index;
			formData.value[type] = procurementDemandTags.value[index].value;
		}
	}
	//获取采购状态
	const getprocurementDemandStatusList = async () => {
		const data = await getShipments('procurement_demand_status', 'tag');
		//
		console.log('getprocurementDemandStatusList --->', data);
		procurementDemandStatusTags.value = [];
		data.forEach((item : any, key : number) => {
			procurementDemandStatusTags.value.push(item);
			//
			if (formData.value.procurementDemandStatusId === item.value) {
				procurementDemandStatusIndex.value = key;
			}
		});
	}
	//获取类型
	const getprocurementDemandList = async () => {
		const data = await getShipments('procurement_demand_type', 'tag');
		//
		console.log('getprocurementDemandList --->', data);
		procurementDemandTags.value = [];
		data.forEach((item : any, key : number) => {
			procurementDemandTags.value.push(item);
			//
			if (formData.value.procurementDemandType === item.value) {
				procurementDemandIndex.value = key;
			}
		});
	}
	//获取所有仓库
	const getwarehouseAll = async () => {
		warehouseOption.value = [];
		const result = await request({
			url: '/demand/warehouseAll',
		});
		//
		console.log('getwarehouseAll --->', result);
		//
		result.data.t.forEach((item : any, key : number) => {
			warehouseOption.value.push({
				label: `${item.warehouseName}`,
				value: item.warehouseId,
				icon: Ticket,
				color: '#ff5500'
			});
			if (formData.value.warehouseId === item.warehouseId) {
				formData.value.warehouse = [item.warehouseId];
				warehouseIndex.value = key;
				//
				getproductById(item.warehouseId);
			}
		});
		//
	}
	//根据id获取仓库商品
	const getproductById = async (id : number) => {
		productOption.value = [];
		const result = await request({
			url: '/demand/productById',
			params: {
				id
			}
		});
		//
		console.log('getproductById --->', result);
		result.data.t.forEach((item : any, key : number) => {
			productOption.value.push({
				label: `${item?.productName}${item?.model} | 在库${item?.currentInventory}件`,
				value: item?.productId,
				icon: UploadFilled,
				color: '#5283ff'
			});
			if (formData.value.productId === item.productId) {
				formData.value.product = [item.productId];
				productIndex.value = key;
				//
			}
		});
		//
		console.log('productOption.value --->', productOption.value);
	}
	//获取所有供应商
	const getexpectedSupplierAll = async () => {
		expectedSupplierOption.value = [];
		const result = await request({
			url: '/demand/supplierAll',
		});
		//
		console.log('getexpectedSupplierAll --->', result);
		//
		result.data.t.forEach((item : any, key : number) => {
			expectedSupplierOption.value.push({
				label: `${item.supplierShortName}`,
				value: item.supplierId,
				icon: Ship,
				color: '#ff5500'
			});
			if (formData.value.expectedSupplierId === item.supplierId) {
				formData.value.expectedSupplier = [item.supplierId];
				expectedSupplierIndex.value = key;
				//
			}
		});
		//
	}
	//提交表单
	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		console.log('submitForm --->');
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				const data = { ...formData.value };
				delete data.expectedSupplier;
				delete data.product;
				delete data.warehouse;
				// console.log('submitForm ---> ', data);
				let type = '';
				if (!route.query.id) {
					type = '/addDemand';
				} else {
					type = '/updateDemand';
				}
				//
				const result = await request({
					url: '/demand' + type,
					data: data,
					method: 'post'
				});
				//
				console.log('submitForm--->', result);
				//

				if (result.data.code === 200) {
					ElMessage.success({
						message: '操作成功！'
					});
					//

					
				} else {
					ElMessage.error({
						message: result.data.msg
					});
				}
				// //
				route.query.id = result.data.t;
				setTimeout(() => {
					closeDialog();
					emits('update');
				}, 1);
			} else {
				//
				console.log('error submit!', fields);
			}
		});
	}
	defineExpose({
		openDialog
	});
</script>
<style>
	@import '../../../assets/css/my-form-item.css';

	.form-item-bg {
		background-color: #bfdfff;
	}

	.form-item-bg1 {
		background-color: #a5f2e5;
	}

	.my.el-input .el-input__inner {
		opacity: 0;
	}

	/*  */
	.avatar-uploader {
		width: 178px;
		height: 178px;
	}

	.avatar-uploader .avatar {
		width: 100%;
		height: 100%;
	}

	.avatar-uploader .el-upload {
		width: 100%;
		height: 100%;
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.el-scrollbar__view {
		display: block !important;
	}

	/*  */
</style>

<style scoped lang="scss">
	@import '../../../assets/css/index.scss';
</style>